# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import xlwt
from .. import format_common
from openerp.tools.translate import _
import cStringIO
from openerp.osv import osv, fields
import os, time
import base64
import logging
_logger = logging.getLogger(__name__)
from xlwt import *

class param_time_sheet_report(osv.osv_memory):
    _name = 'param.time.sheet.report'
    _description = 'Timesheet Report'
    _columns = {
        'filter_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Project Filter Selection', required=True),
        'project_default_from':fields.many2one('project.project', 'Project From', required=False),
        'project_default_to':fields.many2one('project.project', 'Project To', required=False),
        'project_input_from': fields.char('Project From', size=128),
        'project_input_to': fields.char('Project To', size=128),
        'project_name_ids' :fields.many2many('project.project', 'project_name_rel', 'project_name', 'project_id', 'Project'),
        'task_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Task Filter Selection', required=True),
        'project_task_default_from':fields.many2one('project.task', 'Task From', required=False),
        'project_task_default_to':fields.many2one('project.task', 'Task To', required=False),
        'project_task_input_from': fields.char('Task From', size=128),
        'project_task_input_to': fields.char('Task To', size=128),
        'project_task_name_ids' :fields.many2many('project.task', 'project_task_name_rel', 'task_name', 'task_id', 'Project Task'),
        'date_selection': fields.selection([('none_sel','None'),('date_sel', 'Date')],'Date Selection', required=True),
        'date_from': fields.datetime("From Date"),
        'date_to': fields.datetime("To Date"),
        'employee_selection': fields.selection([('all_vall','All'),('def','Default'),('input', 'Input'),('selection','Selection')],'Employee Filter Selection', required=True),
        'employee_default_from':fields.many2one('hr.employee', 'Employee From', required=False),
        'employee_default_to':fields.many2one('hr.employee', 'Employee To', required=False),
        'employee_input_from': fields.char('Employee From', size=128),
        'employee_input_to': fields.char('Employee To', size=128),
        'employee_name_ids' :fields.many2many('hr.employee', 'employee_name_rel', 'name', 'id', 'Employee Name'),
        'department_selection': fields.selection([('all_vall','All'),('selection','Selection')],'Department Filter Selection', required=True),
        'department_name_ids': fields.one2many('param.time.sheet.report.dept','dept_id', 'Department'),
        'sortby_ids': fields.one2many('timesheet.sortby','sortby_id', 'Sort By'),
        'billing_type':fields.selection([('all_vall','All'),('bill','Actual'),
                                 ('unbill','Non Actual'),
                                 ], 'Billing Type'),
    }
    
    _defaults = {
        'filter_selection': 'all_vall',
        'task_selection': 'all_vall',
        'date_selection': 'none_sel',
        'employee_selection': 'all_vall',
        'department_selection': 'all_vall',
        'billing_type': 'all_vall',
    }

    def onchange_filter_selection(self, cr, uid, ids, filter_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if filter_selection != 'all_vall':
             res['value'] = {'project_default_from': False, 'project_default_to': False, 'project_input_from': False, 'project_input_to': False, 'project_name_ids': False,
                                }
        return res
    
    def onchange_task_selection(self, cr, uid, ids, task_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if task_selection != 'all_vall':
             res['value'] = {'project_task_default_from': False, 'project_task_default_to': False, 'project_task_input_from': False, 'project_task_input_to': False, 'project_task_name_ids': False,
                                }
        return res
    
    def onchange_date_selection(self, cr, uid, ids, date_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if date_selection != 'none_sel':
             res['value'] = {'date_from': False, 'date_to': False, 
                                }
        return res
    
    def onchange_employee_selection(self, cr, uid, ids, employee_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if employee_selection != 'all_vall':
             res['value'] = {'employee_default_from': False, 'employee_default_to': False, 'employee_input_from': False, 'employee_input_to': False, 'employee_name_ids': False,
                                }
        return res
    
    def onchange_department_selection(self, cr, uid, ids, department_selection, context=None):
        if context is None:
            context = {}
        res = {}
        if department_selection != 'all_vall':
             res['value'] = {'department_name_ids': False,
                                }
        return res
    
    def _search_data(self, cr, uid, ids, data_obj, val_data, filter_selection, default_from, default_to, input_from, input_to, selection_ids, context=None):
        #Out Default Value
        data_header = ''
        data_ids = []
        #Declaration

        if context is None:
            context = {}
        
#         special_case = 'special_case' in context and context['special_case'] or False
        if filter_selection == 'all_vall':
            data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'def':
            data_found = False
            if default_from and data_obj.browse(cr, uid, default_from) and data_obj.browse(cr, uid, default_from).name:
                default_from_header = data_obj.browse(cr, uid, default_from).name
                data_found = True
                val_data.append(('name', '>=', default_from_header))
            if default_to and data_obj.browse(cr, uid, default_to) and data_obj.browse(cr, uid, default_to).name:
                default_to_header = data_obj.browse(cr, uid, default_to).name
                data_found = True
                val_data.append(('name', '<=', default_to_header))
            if data_found:
                data_header = '"' + default_from_header + '" - "' + default_to_header + '"'
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'input':
            data_found = False
            if input_from:
                data_ids_from = data_obj.search(cr, uid, [('name','=ilike',input_from + '%')], order="name", limit=1)
                if data_ids_from:
                    input_from_name = data_obj.browse(cr, uid, data_ids_from[0]).name
                    data_found = True
                    val_data.append(('name', '>=', input_from_name))
            if input_to:
                data_ids_to = data_obj.search(cr, uid, [('name','=ilike', input_to + '%')], order="name desc", limit=1)
                if data_ids_to:
                    input_to_name = data_obj.browse(cr, uid, data_ids_to[0]).name
                    data_found = True
                    val_data.append(('name', '<=', input_to_name))
            data_header = '"' + input_from + '" - "' + input_to + '"'
            if data_found:
                data_ids = data_obj.search(cr, uid, val_data, order='id ASC')
        if filter_selection == 'selection':
            if selection_ids:
                sel_ids = ''
                for sel in  data_obj.browse(cr, uid, selection_ids):
                    sel_ids += ('"%s",')%(sel.name,)

                data_header = '[' + sel_ids +']'
                data_ids = selection_ids
        return data_header, data_ids

    def _build_contexts(self, cr, uid, ids, data, context=None):
        if context is None:
            context = {}
        result = {}
        result['filter_selection'] = data['form']['filter_selection'] or False
        result['task_selection'] = data['form']['task_selection'] or False
        result['date_selection'] = data['form']['date_selection'] or False
        result['employee_selection'] = data['form']['employee_selection'] or False
        result['department_selection'] = data['form']['department_selection'] or False
        result['sortby_ids'] = data['form']['sortby_ids'] or False
        result['department_name_ids'] = data['form']['department_name_ids'] or False
        result['billing_type'] = data['form']['billing_type'] or False
        
        result['output_project_header'], result['project_ids'] = self._search_data(cr, uid, ids, self.pool.get('project.project'),
                                                                                      [('state','!=','cancelled')],
                                                                                      data['form']['filter_selection'],
                                                                                      data['form']['project_default_from'] or False,
                                                                                      data['form']['project_default_to'] or False,
                                                                                      data['form']['project_input_from'] or False,
                                                                                      data['form']['project_input_to'] or False,
                                                                                      data['form']['project_name_ids'] or False,
                                                                                      context=context)

        result['output_task_header'], result['task_ids'] = self._search_data(cr, uid, ids, self.pool.get('project.task'),
                                                                                      [],
                                                                                      data['form']['task_selection'],
                                                                                      data['form']['project_task_default_from'] or False,
                                                                                      data['form']['project_task_default_to'] or False,
                                                                                      data['form']['project_task_input_from'] or False,
                                                                                      data['form']['project_task_input_to'] or False,
                                                                                      data['form']['project_task_name_ids'] or False,
                                                                                      context=context)
        
        result['output_emp_header'], result['emp_ids'] = self._search_data(cr, uid, ids, self.pool.get('hr.employee'),
                                                                                      [],
                                                                                      data['form']['employee_selection'],
                                                                                      data['form']['employee_default_from'] or False,
                                                                                      data['form']['employee_default_to'] or False,
                                                                                      data['form']['employee_input_from'] or False,
                                                                                      data['form']['employee_input_to'] or False,
                                                                                      data['form']['employee_name_ids'] or False,
                                                                                      context=context)
                
        date_from = data['form']['date_from']
        date_to = data['form']['date_to']
        
        output_date_header = ''
        val_date = []
        if data['form']['date_selection'] == 'date_sel':
            if date_from and not date_to:
                output_date_header = 'Date Start From : %s' % (date_from,)
                val_date.append(('date','>=',str(date_from)))
            elif date_to and not date_from:
                output_date_header = 'Date Until : %s' % (date_to,)
                val_date.append(('date','<=',str(date_to))) 
            elif date_to and date_from:
                output_date_header = 'Date Start From : %s, Until: %s' % (date_from, date_to)
                val_date.append(('date','>=',str(date_from)))
                val_date.append(('date','<=',str(date_to)))

        result['output_date_header'] = output_date_header
        result['val_date'] = val_date
        
        output_billing_header = ''
        val_billing = []
        if data['form']['billing_type'] == 'bill':
            val_billing.append(('task_id.project_id.analytic_account_id.billing_type','=','bill'))
            output_billing_header = "Actual"
        elif data['form']['billing_type'] == 'unbill':
            val_billing.append(('task_id.project_id.analytic_account_id.billing_type','=','unbill'))
            output_billing_header = "Non Actual"

        result['output_billing_header'] = output_billing_header
        result['val_billing'] = val_billing
        
        return result
    
    def create_vat(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        datas = {'ids': context.get('active_ids', [])}
        datas['model'] = 'param.time.sheet.report'
        datas['form'] = self.read(cr, uid, ids)[0]
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'timesheet.report_landscape',
            'datas': datas,
            'nodestroy':True,
        }
    
    def print_report(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        data = {}
        data['ids'] = context.get('active_ids', [])
        data['model'] = context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(cr, uid, ids, ['filter_selection','project_default_from','project_default_to','project_input_from','project_input_to', 'project_name_ids', \
                                                'task_selection','project_task_default_from','project_task_default_to','project_task_input_from','project_task_input_to', 'project_task_name_ids', \
                                                'employee_selection','employee_default_from','employee_default_to','employee_input_from','employee_input_to', 'employee_name_ids', \
                                                'department_selection', 'department_name_ids', \
                                                'date_selection', 'date_from', 'date_to', 'sortby_ids','billing_type' ], context=context)[0]
        for field in ['filter_selection','project_default_from','project_default_to','project_input_from','project_input_to', 'project_name_ids', \
                      'task_selection','project_task_default_from','project_task_default_to','project_task_input_from','project_task_input_to', 'project_task_name_ids', \
                      'employee_selection','employee_default_from','employee_default_to','employee_input_from','employee_input_to', 'employee_name_ids', \
                      'department_selection','department_name_ids','sortby_ids', 'billing_type', \
                      'date_selection', 'date_from', 'date_to']:
            if isinstance(data['form'][field], tuple):
                data['form'][field] = data['form'][field][0]   
        used_context = self._build_contexts(cr, uid, ids, data, context=context)

        return self._get_tplines_xls(cr, uid, ids, used_context, context=context)
        
    def _get_tplines_xls(self, cr, uid, ids, form, context):

        if not ids:
            ids = data['ids']
        if not ids:
            return []
        
        user_obj = self.pool.get('res.users')
        project_task_work_obj = self.pool.get('project.task.work')
        timesheet_sortby_obj = self.pool.get('timesheet.sortby')
        emp_obj = self.pool.get('hr.employee')
        dept_obj = self.pool.get('param.time.sheet.report.dept')
        
        result        = []
        results       = []
        val_task_work = []
        dept          = []
        dept_sel      = []
        
        project_ids = form['project_ids']
        task_ids = form['task_ids']
        emp_ids = form['emp_ids']
        dept_ids = form['department_name_ids']
        output_project_header = form['output_project_header']
        output_task_header = form['output_task_header']
        output_date_header = form['output_date_header']
        output_emp_header = form['output_emp_header']
        output_billing_header = form['output_billing_header']
        output_dept_header = output_sortby_header = ''
        bill_name = department_name = dept_str  = ''

        if project_ids:
            val_task_work.append(('task_id.project_id','in',project_ids))
        if task_ids:
            val_task_work.append(('task_id','in',task_ids))
        user_ids = []
        if emp_ids:
            for emp_id in emp_obj.browse(cr, uid, emp_ids):
                if emp_id.user_id:
                    user_ids.append(emp_id.user_id.id)
            val_task_work.append(('user_id','in',user_ids))
        
        if form['department_selection'] != 'all_vall':
            department_ids = dept_obj.search(cr, uid, [('id', 'in', form['department_name_ids'])])
            for dept in dept_obj.browse(cr, uid, department_ids):
                dept_sel.append((dept['name']))
 
            for rs in dept_sel:
                dept_name = ''
                if rs == 'shipyard':
                    dept_name = 'Shipyard'
                elif rs == 'mechanical':
                    dept_name = 'Mechanical'
                elif rs == 'electrical':
                    dept_name = 'Electrical'
                elif rs == 'welding_fabrication':
                    dept_name = 'Welding & Fabrication'
                elif rs == 'interior':
                    dept_name = 'Interior'
                elif rs == 'design':
                    dept_name = 'Design'
                elif rs == 'other_dept1':
                    dept_name = user_obj.browse(cr, uid, uid).company_id.dept1_alias or 'Department1'
                elif rs == 'other_dept2':
                    dept_name = user_obj.browse(cr, uid, uid).company_id.dept2_alias or 'Department2'
                elif rs == 'other_dept3':
                    dept_name = user_obj.browse(cr, uid, uid).company_id.dept3_alias or 'Department3'
                
                
                dept_str += ('"%s",')%(dept_name,)
            val_task_work.append(('department','in',dept_sel))
            output_dept_header = '[' + dept_str + ']'
            
        if 'val_date' in form:
            val_task_work += form['val_date']
        
        if 'val_billing' in form:
            val_task_work += form['val_billing']
        
        timesheet_sortby_ids = []
        if 'sortby_ids' in form:
            timesheet_sortby_ids = timesheet_sortby_obj.search(cr, uid, [('id', 'in', form['sortby_ids'])], order='seq desc')
        
        if timesheet_sortby_ids:
            for item in timesheet_sortby_obj.browse(cr, uid, timesheet_sortby_ids):
                result.append({
                        'seq' : item['seq'],
                        'sort_by' : item['sort_by'],
                        })
            result = result and sorted(result, key=lambda val_res: val_res['seq']) or []               
            
            for rs in result:
                sort_name = ''
                if rs['sort_by'] == 'project_name':
                    sort_name = 'Project'
                elif rs['sort_by'] == 'task_name':
                    sort_name = 'Task'
                elif rs['sort_by'] == 'date_ptw':
                    sort_name = 'Date'
                elif rs['sort_by'] == 'emp_name':
                    sort_name = 'Employee'
                elif rs['sort_by'] == 'dept':
                    sort_name = 'Department'
                elif rs['sort_by'] == 'billing':
                    sort_name = 'Billing'
                output_sortby_header += ('"%s",')%(sort_name,)
        
        project_task_work_ids = project_task_work_obj.search(cr, uid, val_task_work)
        if project_task_work_ids:
            ptw_ids = []
            
            for ptw in project_task_work_obj.browse(cr, uid, project_task_work_ids):
                emp_id = emp_obj.search(cr, uid, [('user_id', '=', ptw.user_id.id)])
                emp_name = (emp_id and emp_obj.browse(cr, uid, emp_id[0]).name) or ''
                emp_no = (emp_id and emp_obj.browse(cr, uid, emp_id[0]).employee_no) or ''
                ptw_ids.append({
                    'project_name' : ptw.task_id.project_id.name,
                    'task_name' : ptw.task_id.name,
                    'date_ptw' : ptw.date,
                    'emp_name' : emp_name,
                    'dept' : ptw.department,
                    'emp_no' : emp_no,
                    'type' : ptw.type,
                    'ptw_hours' : ptw.hours,
                    'billing' : ptw.task_id.project_id.analytic_account_id.billing_type,
                })
            if timesheet_sortby_ids:
                for timesheet_sortby in timesheet_sortby_obj.browse(cr, uid, timesheet_sortby_ids):
                    ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res[timesheet_sortby.sort_by]) or []               
            else:
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['billing']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['dept']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['emp_name']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['date_ptw']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['task_name']) or []
                ptw_ids = ptw_ids and sorted(ptw_ids, key=lambda val_res: val_res['project_name']) or []
            
            for ptw_result in ptw_ids:
                results.append({
                    'project_name' : ptw_result['project_name'] or '',
                    'task_name' : ptw_result['task_name'] or '',
                    'date_ptw' : ptw_result['date_ptw'] or '',
                    'emp_name' : ptw_result['emp_name'] or '',
                    'dept' : ptw_result['dept'] or '',
                    'emp_no' : ptw_result['emp_no'] or '',
                    'type' : ptw_result['type'] or '',
                    'ptw_hours' : ptw_result['ptw_hours'] or 0.0,
                    'billing' : ptw_result['billing'] or '',
                })
                
        workbook = xlwt.Workbook()
        M_header_tstyle = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=300)
        report_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=190)
        report_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        header_tstyle = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        header_tstyle_c = format_common.font_style(position='center', bold=1, border=7, fontos='black', font_height=180)
        header_tstyle_l = format_common.font_style(position='left', bold=1,border=7, fontos='black', font_height=180)
        header_tstyle_c_Top = format_common.font_style(position='center', bold=1, border=4, fontos='black', font_height=180)
        header_tstyle_c_Bottom = format_common.font_style(position='center', bold=1, border=3, fontos='black', font_height=180)
        header_tstyle_r = format_common.font_style(position='right', bold=1,  border=7,fontos='black', font_height=180)
        view_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        view_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        view_tstyle_l = format_common.font_style(position='left', fontos='black', font_height=180)
        view_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        view_tstyle_r_b = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        other_tstyle = format_common.font_style(position='left', fontos='black', font_height=180)
        other_tstyle_c = format_common.font_style(position='center', fontos='black', font_height=180)
        other_tstyle_r = format_common.font_style(position='right', fontos='black', font_height=180)
        text_tstyle = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        text_tstyle1 = format_common.font_style(position='left', bold=1, fontos='black', font_height=220)
        text_tstyle2 = format_common.font_style(position='left', fontos='black', font_height=220)
        text_tstyle_c = format_common.font_style(position='center', bold=1, fontos='black', font_height=180)
        text_tstyle_l = format_common.font_style(position='left', bold=1, fontos='black', font_height=180)
        text_tstyle_r = format_common.font_style(position='right', bold=1, fontos='black', font_height=180)
        text_tstyle_r_closing = format_common.font_style(position='right', bold=1,border=7, fontos='black', font_height=180)
        text_tstyle_Top = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Bottom = format_common.font_style(position='left', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_Top_r = format_common.font_style(position='right', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_l = format_common.font_style(position='left', bold=1, border=4, fontos='black', font_height=180)
        text_tstyle_Top_r_r = format_common.font_style(position='right', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Top_l_l = format_common.font_style(position='left', bold=1, border=6, fontos='black', font_height=180)
        text_tstyle_Bottom_r = format_common.font_style(position='right', bold=1, border=3, fontos='black', font_height=180)
        text_tstyle_TopBottom = format_common.font_style(position='left', bold=1, border=2, fontos='black', font_height=180)
        text_tstyle_TopBottom_r = format_common.font_style(position='right', bold=1, border=2, fontos='black', font_height=180)
        
        sheet = workbook.add_sheet('Timesheet Report XLS')
        sheet.row(0).height = 350
        row=0
        
        company_name = user_obj.browse(cr, uid, uid).company_id.name
        sheet.write_merge(row, row, 0, 8, company_name, report_tstyle1)
        
        row+=1
        sheet.write_merge(row, row, 0, 8, 'Timesheet Report', report_tstyle1)
        
        user_ids = user_obj.search(cr, uid, [('id','=',uid)])
        if user_ids :
            tz = user_obj.browse(cr, uid, user_ids[0])
            tz_name = tz.tz
            user_name = tz.name
            
        os.environ['TZ'] = tz_name
        time.tzset()
        
        row+=1
        sheet.write_merge(row, row, 0, 2, 'Printed date : ' + time.strftime("%Y/%m/%d") + '  Time : '+ time.strftime("%H:%M:%S"), view_tstyle)
        sheet.write_merge(row, row, 3, 5, 'Printed by : ' + user_name, view_tstyle)
        
        row+=1
        sheet.write(row, 0, '', view_tstyle)
        
        if form['filter_selection'] != 'all_vall' :
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Project : ' + output_project_header, text_tstyle)
        
        if form['task_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Task : ' + output_task_header, text_tstyle)
        
        if form['date_selection'] != 'none_sel':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   ' + output_date_header, text_tstyle)
        
        if form['employee_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Employee : ' + output_emp_header, text_tstyle)
        
        if form['department_selection'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Department : ' + output_dept_header, text_tstyle)
        
        if form['billing_type'] != 'all_vall':
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Billing : "' + output_billing_header + '"', text_tstyle)
        
        if form['sortby_ids']:
            row += 1
            sheet.write_merge(row, row, 0, 8, '   Sort By : ' + output_sortby_header, text_tstyle)
        
        row+=1
        sheet.write(row, 0, '', view_tstyle)
        
        row+=1
        sheet.write(row, 0, 'Project', header_tstyle_c)
        sheet.write(row, 1, 'Task', header_tstyle_c)
        sheet.write(row, 2, 'Date', header_tstyle_c)
        sheet.write(row, 3, 'Employee Name', header_tstyle_c)
        sheet.write(row, 4, 'Department', header_tstyle_c)
        sheet.write(row, 5, 'Employee No', header_tstyle_c)
        sheet.write(row, 6, 'Hours', header_tstyle_c)
        sheet.write(row, 7, 'Type', header_tstyle_c)
        sheet.write(row, 8, 'Billing', header_tstyle_c)
         
        sheet.col(0).width = 256 * 18
        sheet.col(1).width = 256 * 18
        sheet.col(2).width = 256 * 20
        sheet.col(3).width = 256 * 20
        sheet.col(4).width = 256 * 20
        sheet.col(5).width = 256 * 15
        sheet.col(6).width = 256 * 8
        sheet.col(7).width = 256 * 8
        sheet.col(8).width = 256 * 10
        
        for rs1 in results:
            row += 1
            sheet.write(row, 0, str(rs1['project_name']), view_tstyle_l)
            sheet.write(row, 1, str(rs1['task_name']), view_tstyle_l)
            sheet.write(row, 2, str(rs1['date_ptw']), view_tstyle_l)
            sheet.write(row, 3, str(rs1['emp_name']), view_tstyle_l)
            
            if rs1['dept'] == 'shipyard':
                department_name = 'Shipyard'
            elif rs1['dept'] == 'mechanical':
                department_name = 'Mechanical'
            elif rs1['dept'] == 'electrical':
                department_name = 'Electrical'
            elif rs1['dept'] == 'welding_fabrication':
                department_name = 'Welding & Fabrication'
            elif rs1['dept'] == 'interior':
                department_name = 'Interior'
            elif rs1['dept'] == 'design':
                department_name = 'Design'
            elif rs1['dept'] == 'other_dept1':
                department_name = user_obj.browse(cr, uid, uid).company_id.dept1_alias or 'Department1'
            elif rs1['dept'] == 'other_dept2':
                department_name = user_obj.browse(cr, uid, uid).company_id.dept2_alias or 'Department2'
            elif rs1['dept'] == 'other_dept3':
                department_name = user_obj.browse(cr, uid, uid).company_id.dept3_alias or 'Department3'
            
            sheet.write(row, 4, department_name, view_tstyle_l)
            sheet.write(row, 5, str(rs1['emp_no']), view_tstyle_l)
            sheet.write(row, 6, str(rs1['ptw_hours']), view_tstyle_r)
            sheet.write(row, 7, str(rs1['type']), view_tstyle_l)
            
            if rs1['billing'] == 'bill':
                bill_name = 'Actual'
            elif rs1['billing'] == 'unbill':
                bill_name = 'Non Actual'
            
            sheet.write(row, 8, bill_name, view_tstyle_l)
        
        row += 1
        sheet.write_merge(row, row, 0, 8, 'End of Report', text_tstyle_Top_l) 
        
        stream = cStringIO.StringIO()
        workbook.save(stream)
            
        cr.execute(""" DELETE FROM output""")
        attach_id = self.pool.get('output').create(cr, uid, {'name':'Timesheet Report.xls', 'xls_output':base64.encodestring(stream.getvalue())})
        return {
                'name': _('Notification'),
                'context': context,
                'view_type': 'form',
                'view_mode': 'form',
                'res_model': 'output',
                'res_id':attach_id,
                'type': 'ir.actions.act_window',
                'target':'new'
                }

class timesheet_sortby(osv.osv_memory):
    
    _name = "timesheet.sortby"
    
    _columns = {
        'sortby_id': fields.many2one('param.time.sheet.report', 'Sort By', required=True, ondelete='cascade'),
        'seq': fields.integer('Sequence', required=True),
        'sort_by': fields.selection([('project_name','Project'),('task_name', 'Task'), ('date_ptw', 'Date'), ('emp_name', 'Employee'), ('dept', 'Department'), ('billing', 'Billing')],'Sort by', required=True),
    }

class param_time_sheet_report_dept(osv.osv_memory):
    
    _name = "param.time.sheet.report.dept"
    
    _columns = {
        'dept_id': fields.many2one('param.time.sheet.report', 'Department', required=True, ondelete='cascade'),
        'name':fields.selection([('shipyard','Shipyard'),
                                 ('mechanical','Mechanical'),
                                 ('electrical','Electrical'),
                                 ('welding_fabrication','Welding & Fabrication'),
                                 ('interior','Interior'),
                                 ('design','Design'),
                                 ('other_dept1','Other Dept1'),
                                 ('other_dept2','Other Dept2'),
                                 ('other_dept3','Other Dept3')
                                 ], 'Department', required=True),
    }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
